package cn.breeze.system.service.impl;

import cn.breeze.system.domain.Menu;
import cn.breeze.system.domain.Role;
import cn.breeze.system.mapper.RoleMapper;
import cn.breeze.system.service.IRoleService;
import cn.breeze.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author breeze
 * @since 2022-07-11
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void remove(Long id) {
        // 根据id删除menu中间表信息
        roleMapper.removeRoleIdMenu(id);
        // 根据id删除Permission中间表信息
        roleMapper.removeRoleIdPermission(id);
        // 删除role表
        roleMapper.remove(id);
    }

    @Override
    public void save(Role role) {
        initRoleMenuPermission(role);
    }

    @Override
    public void update(Role role) {
        initRoleMenuPermission(role);
    }

    @Override
    public void patchRemove(Long[] ids) {
        // 根据id删除menu中间表信息
        roleMapper.patchRemoveRoleIdMenu(ids);
        // 根据id删除Permission中间表信息
        roleMapper.patchRemoveRoleIdPermission(ids);
        // 删除role表
        roleMapper.patchRemove(ids);
    }

    /**
    * @Title: initRoleMenuPermission
    * @Description: 初始化role
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/13 12:43
    * @Parameters: [role]
    * @Return void
    */
    public void initRoleMenuPermission(Role role){
        Long id = role.getId();
        if (role.getId() != null){
            // 根据id删除menu中间表信息
            roleMapper.removeRoleIdMenu(id);
            // 根据id删除Permission中间表信息
            roleMapper.removeRoleIdPermission(id);
            // 保存role
            roleMapper.update(role);
        } else {
            // 保存role
            roleMapper.save(role);
        }
        // 保存menu
        if (role.getMenus() != null){
            roleMapper.saveRoleMenu(id, role.getMenus());
        }
        if (role.getPermissions() != null){
            roleMapper.saveRolePermission(id, role.getPermissions());
        }
    }

    /**
    * @Title: ownMenus
    * @Description: 获取所有菜单
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/13 23:12
    * @Parameters: [id]
    * @Return java.util.List<cn.breeze.system.domain.Menu>
    */
    @Override
    public List<Menu> ownMenus(Long id) {
        return roleMapper.ownMenus(id);
    }

    @Override
    public Long[] loaadPermissions(Long id) {
        return roleMapper.loaadPermissions(id);
    }

    /**
    * @Title: loadByEmpId
    * @Description: 根据employee获取所有角色
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/15 1:17
    * @Parameters: [id]
    * @Return cn.breeze.system.domain.Role
     * @return
    */
    @Override
    public List<Long> loadByEmpId(Long id) {
        return roleMapper.loadByEmpId(id);
    }
}
